package com.kuaimacode.kframework.admin.controller.master;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.kuaimacode.kframework.admin.services.account.UserAccountDetailServices;
import com.kuaimacode.kframework.admin.services.agent.SysAgentService;
import com.kuaimacode.kframework.admin.services.finance.AgentAccountDetailService;
import com.kuaimacode.kframework.admin.services.master.MasterDrawApplyService;
import com.kuaimacode.kframework.admin.services.master.MasterService;
import com.kuaimacode.kframework.admin.services.sysparam.SysParamService;
import com.kuaimacode.kframework.admin.services.user.SysAdminUserService;
import com.kuaimacode.kframework.admin.services.user.UserService;
import com.kuaimacode.kframework.admin.util.SessionUtil;
import com.kuaimacode.kframework.admin.vo.request.MasterDrawApplyReq;
import com.kuaimacode.kframework.admin.vo.request.MasterReq;
import com.kuaimacode.kframework.common.JsonResult;
import com.kuaimacode.kframework.constants.PageConstants;
import com.kuaimacode.kframework.mybatis.models.admin.SysAdminUser;
import com.kuaimacode.kframework.mybatis.models.agent.SysAgent;
import com.kuaimacode.kframework.mybatis.models.finance.AgentAccountDetail;
import com.kuaimacode.kframework.mybatis.models.master.UserMaster;
import com.kuaimacode.kframework.mybatis.models.sysparam.SysParam;
import com.kuaimacode.kframework.mybatis.models.user.MasterAccountResult;
import com.kuaimacode.kframework.mybatis.models.user.User;
import com.kuaimacode.kframework.mybatis.models.user.UserAccountDetail;
import com.kuaimacode.kframework.mybatis.models.user.UserDrawApply;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.spring.web.json.Json;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;

/**
 * @author 12786 on 2019/5/25.
 * @version 1.0
 */
@Controller
@RequestMapping({"/masterdraw"})
public class MasterDrawApplyController {

    private static String PAGE_FILE_NAME = "masterdraw/";

    @Autowired
    private MasterDrawApplyService drawApplyService;

    @Autowired
    private UserAccountDetailServices detailServices;

    @Autowired
    private UserService userService;

    @Autowired
    private AgentAccountDetailService detailService;

    @Autowired
    private SysParamService sysParamService;

    @Autowired
    private MasterService masterService;

    @Autowired
    private SysAgentService agentService;

    @Autowired
    private AgentAccountDetailService agentDetailService;

    @Autowired
    private UserAccountDetailServices userAccService;

    @Autowired
    private SysAdminUserService adminUserService;





    @RequestMapping(value = {"/drawapply"})
    public String drawapply(@RequestParam(value = "pageNum", required = true, defaultValue = PageConstants.PAGE_NUM+"") int pageNum,
                            @RequestParam(value = "pageSize", required = true, defaultValue = PageConstants.PAGE_SIZE+"") int pageSize,
                            MasterDrawApplyReq masterDrawApplyReq, ModelMap model) {
        PageInfo<MasterAccountResult> pageInfo = drawApplyService.getMasterDrawApply(masterDrawApplyReq,pageNum, pageSize);
        // pageInfo.list master
        model.put("pageInfo", pageInfo);
        model.put("masterDrawApplyReq", masterDrawApplyReq);
        return PAGE_FILE_NAME + "drawapply";
    }

    @RequestMapping(value = {"/agree/{id}"}, method = RequestMethod.POST)
    @ResponseBody
    public JsonResult agree(@PathVariable String id, ModelMap map) {
        UserDrawApply userDrawApply = drawApplyService.getById(id);
        userDrawApply.setApplyStatus("2");
        SysAdminUser adminUser = adminUserService.getById(SessionUtil.getUserId());
        String processName = adminUser.getRealName();
        userDrawApply.setProcessName(processName);
        if (drawApplyService.updateById(userDrawApply)){
            User user = userService.getById(userDrawApply.getUserId());
            BigDecimal applyAmount = new BigDecimal(StringUtils.isEmpty(userDrawApply.getApplyAmount())?"0":userDrawApply.getApplyAmount());
            BigDecimal blockAmount = new BigDecimal(StringUtils.isEmpty(userDrawApply.getBlockAmount())?"0":userDrawApply.getBlockAmount());
            BigDecimal accountBlance = user.getAccountBalance();
            if (accountBlance == null) {
                accountBlance = new BigDecimal(0);
            }
            if (accountBlance.compareTo(BigDecimal.ZERO)==1){
                //大于零那么
                BigDecimal account = new BigDecimal(0);
                //手续费比例
                QueryWrapper<SysParam> query = new QueryWrapper<>();
                query.eq("name","WITHDRAW_RATE");
                SysParam param = sysParamService.getOne(query);
                BigDecimal sxfee = BigDecimal.ZERO;
                if (param !=null&&StringUtils.isNotEmpty(param.getValue())){
                    //手续费
                    sxfee = (applyAmount.subtract(blockAmount)).multiply(new BigDecimal(param.getValue()).multiply(new BigDecimal("0.01")).setScale(2,BigDecimal.ROUND_HALF_DOWN));
                }
                accountBlance = accountBlance.add(blockAmount);
                user.setAccountBalance(accountBlance);
                if (userService.updateById(user)){
                    //手续费存入平台账户
                    if (insertPlatForm(sxfee,id,true)){
                        return JsonResult.failure("审批成功");
                    }
                }
            }
        }
        return JsonResult.failure("审批失败");
    }

    @RequestMapping(value = {"/delete/{id}"}, method = RequestMethod.POST)
    @ResponseBody
    public JsonResult delete(@PathVariable String id, ModelMap map) {
        UserDrawApply drawApply = drawApplyService.getById(id);
        drawApply.setApplyStatus("3");
        User user = userService.getById(drawApply.getUserId());
        BigDecimal balance = user.getAccountBalance().add(new BigDecimal(drawApply.getApplyAmount())).setScale(2,BigDecimal.ROUND_HALF_DOWN);
        user.setAccountBalance(balance);
        //拒绝手续费退回用户，用户全额增加
        if (userService.updateById(user)){
            if (drawApplyService.updateById(drawApply)){
                //个人余额明细
                insertUserAccountDetail(balance,new BigDecimal(drawApply.getApplyAmount()).setScale(2, BigDecimal.ROUND_HALF_DOWN),user.getId());
                //平台余额减及平台交易明细
//                insertPlatForm(drawApply.getBrokerage(),String.valueOf(drawApply.getId()),false);
            }
        }
        return JsonResult.success();
    }

    @RequestMapping(value = {"/blockAccmout"})
    @ResponseBody
    public JsonResult blockAccmout(UserDrawApply drawApply,ModelMap modelMap) {
        try {
            drawApplyService.updateById(drawApply);
        } catch (Exception e) {
            return JsonResult.failure(e.getMessage());
        }
        return JsonResult.success();
    }

    @RequestMapping(value = "/blockAccmout/{id}", method = RequestMethod.GET)
    public String blockAccmout(@PathVariable String id, ModelMap map) {
        UserDrawApply drawApply = drawApplyService.getById(id);
        map.put("drawApply",drawApply) ;
        map.put("isAdd", false);
        return PAGE_FILE_NAME+"blockAccmout";
    }

    private boolean insertPlatForm(BigDecimal sxfee, String transId,boolean flag){
        String agentCode = "000000";
        SysAgent agent = agentService.getById(agentCode);
        //平台收取手续费
        Date now = new Date();
        BigDecimal agentTo = agent.getBalance();
        //平台余额增加手续费
        BigDecimal newAgentTo = BigDecimal.ZERO;
        String inout = "1";
        String tranType = "11";
        String tranDesc = "提现手续费";
        if (flag){
            newAgentTo = agentTo.add(sxfee);
        }else{
            newAgentTo = agentTo.subtract(sxfee);
            inout = "2";
            tranType = "4";
            tranDesc = "提现失败手续费退回";
        }
        agent.setBalance(newAgentTo);
        if (agentService.updateById(agent)){
            //添加分站000000收益明细
            AgentAccountDetail agetnDetail = new AgentAccountDetail();
            agetnDetail.setStatus("0");
            agetnDetail.setAmount(sxfee);
            agetnDetail.setTranBal(newAgentTo);
            agetnDetail.setTranType(tranType);
            agetnDetail.setTranTime(now);
            agetnDetail.setTranDesc(tranDesc);
            agetnDetail.setInOut(inout);
            agetnDetail.setAgentId(agentCode);
            agetnDetail.setTranId(transId);
            if (agentDetailService.save(agetnDetail)){
                return Boolean.TRUE;
            }
        }
        return Boolean.FALSE;
    }

    private boolean insertUserAccountDetail(BigDecimal tranAmount,BigDecimal amount,Long userId){
        Date now = new Date();
        UserAccountDetail accountDetail = new UserAccountDetail();
        accountDetail.setTranAmount(tranAmount);
        accountDetail.setAccountType("1");
        accountDetail.setAmount(String.valueOf(amount));
        accountDetail.setCreateDt(now);
        accountDetail.setInOutType("10");
        accountDetail.setUserId(userId);
        accountDetail.setStatus("1");
        accountDetail.setAccoutWay(4L);
        accountDetail.setDetailType("2");
        accountDetail.setUpdateDt(now);
        accountDetail.setTranDesc("提现被拒绝");
        if (userAccService.save(accountDetail)){
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

}
